<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import {
  getMaterialListApi,
  getSimpleClassificationListApi,
} from '@/api/electrical'
import { Search, Refresh, Delete } from '@element-plus/icons-vue'
import TreeSelect from '@/components/TreeSelect/index.vue'
import { ElectricalControlMaterialListParam } from '@/api/electrical/type.ts'

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()



// 添加表格引用
const tableRef = ref()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<ElectricalControlMaterialListParam>({
  classificationId: undefined,
  name: undefined,
  brand: undefined,
  page: 1,
  limit: 10,
})
// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.classificationId = undefined
  searchForm.name = undefined
  searchForm.brand = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getMaterialListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
      setTimeout(() => {
        tableData.value.forEach((row: any) => {
          const isSelected = selectedMaterials.value.some(
              (material: any) => material.id === row.id
          )
          console.log("数据重置选中:"+isSelected)
          if (isSelected) {
            tableRef.value.toggleRowSelection(row, true)
          }
        })
      },300)

    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}
// 保存已经选择的物料
const selectedMaterials = ref<any[]>([])



// ----------------------- 左侧筛选树形数据处理 -----------------------
// 当前选中的分类ID，用于树形筛选
const currentCategoryId = ref<number>()


// ----------------------- 左侧筛选树形数据处理 -----------------------
// 定义树节点类型
interface TreeNode {
  id: string
  name: string
  parentId: string
  children: TreeNode[]
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])

/**
 * 获取左侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getSimpleClassificationListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

/**
 * 处理左侧筛选树形结构
 * @param data 原始数据
 * @returns 处理后的树形数据，包含虚拟顶级节点
 */
const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  // 创建虚拟的顶级节点
  const rootNode: TreeNode = {
    id: '-1',
    name: '全部分类',
    parentId: '',
    children: [],
  }

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)!
    if (item.parentId === '0') {
      rootNode.children.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  result.push(rootNode)
  return result
}

/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击事件
  if (data.id === '-1') {
    currentCategoryId.value = undefined;
    searchForm.classificationId = undefined;
  } else {
    currentCategoryId.value = data.id;
    searchForm.classificationId = data.id;
  }
  // 重置分页
  paginationData.currentPage = 1;
  await getTableData();
}
// 选择电控物料  selection：全部选中的数据     当前点击数据row
const handleSelect = (selection:[], row: any) => {
  // 判断是选中还是取消
 const isSelected =  selection.some(item=>{
   return  item == row
  })
  if(isSelected) {  //勾选了则添加到已选数组中
    selectedMaterials.value.push(row)
  } else {
    selectedMaterials.value = selectedMaterials.value.filter(item=>{
      return item.id != row.id
    })
  }
  console.log("是否选择："+isSelected);
  console.log("已选数据："+selection.length);
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 全选
const handleSelectAll = (selection: any[]) => {
  // 判断是全选还是取消全选
  const isSelected = selection.length === tableData.value.length
  if (isSelected) {
    // 循环全选的数据判断这些数据中是否包含了之前就选择了的数据
    selection.forEach(item=>{
      const some = selectedMaterials.value.some((row: any) => row.id === item.id);
      if(!some) {
        selectedMaterials.value.push(item)
      }
    })
  } else {
    // 清空当前tableData中的已选数据
    selectedMaterials.value = selectedMaterials.value.filter((item: any) => {
      return !tableData.value.some((row: any) => row.id === item.id)
    })
  }
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 确认选择完毕
const confirmMaterial = () => {
  emit('confirmMaterialSelect')
}

// 关闭弹框
const closeDialog = () => {
  onClose()
}

// 删除单个已选物料
const removeMaterial = (material: any, index: number) => {
  // 从已选列表中移除
  selectedMaterials.value.splice(index, 1)
  
  // 同步更新表格选中状态
  if (tableRef.value) {
    // 找到表格中对应的行并取消选中
    const tableRow = tableData.value.find((row: any) => row.id === material.id)
    if (tableRow) {
      tableRef.value.toggleRowSelection(tableRow, false)
    }
  }
  
  // 触发父组件回调
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 清空所有已选物料
const clearAllSelected = () => {
  // 清空已选列表
  selectedMaterials.value = []
  
  // 清空表格选中状态
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  
  // 触发父组件回调
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  dialog.height = 500
  dialog.width = 1200
  dialog.title = '选择电控物料'
  getTreeData()
  getTableData()
  nextTick(() => {
    tableHeight.value = 380
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = 380
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})


// 暴露方法给父组件
defineExpose({
  onShow: (preSelectedMaterials = []) => {
    // 如果传入了预选物料列表，设置为已选中状态
    dialog.visible = true
    selectedMaterials.value= preSelectedMaterials
    // 如果有预选物料，设置表格的选中状态
    if (preSelectedMaterials && preSelectedMaterials.length > 0) {
      // 等待表格数据加载完成后设置选中状态
      nextTick(() => {
        setTimeout(() => {
          if (tableRef.value) {
            // 先清除所有选中状态
            tableRef.value.clearSelection()
            // 设置选中状态
            tableData.value.forEach((row: any) => {
              const isSelected = preSelectedMaterials.some(
                (material: any) => material.id === row.id
              )
              if (isSelected) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
        }, 300)
      })
    }
  },
  onClose,
})

// 定义emit事件
const emit = defineEmits([
  'handleMaterialSelectionChange',
  'confirmMaterialSelect',
  'handleMaterialSelect',
])

// 接收父组件参数
const props = defineProps({
  multiple: {
    type: Boolean,
    default: true,
  },
})

// 点击选择某一行，获取那行的数据
const handleRowClick = (row: any) => {
  if (!props.multiple) {
    emit('handleMaterialSelect', row)
    closeDialog()
  }
}
</script>

<template>
  <sys-dialog :title="dialog.title"
              :width="dialog.width"
              :visible="dialog.visible"
              :height="dialog.height"
              @onClose="closeDialog"
              @on-confirm="confirmMaterial">
    <template #content>
      <div class="material-dialog-container">
        <el-row :gutter="10">
          <!-- 左侧树形菜单 -->
          <el-col :span="5">
            <TreeSelect :data="treeData"
                        :props="{
                  children: 'children',
                  label: 'name'
                }"
                        placeholder="请输入分类名称"
                        @node-click="handleTreeNodeClick"
          class="process-tree"  />


          </el-col>
          <!-- 中间内容区 -->
          <el-col :span="16">
            <!-- 查询表单区域 -->
            <el-card class="search-card">
              <el-form :inline="true"
                       :model="searchForm"
                       class="search-form">
                <el-form-item label="材料名称">
                  <el-input v-model="searchForm.name"
                            placeholder="请输入材料名称" />
                </el-form-item>
                <el-form-item label="品牌">
                  <el-input v-model="searchForm.brand"
                            placeholder="请输入品牌" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary"
                             @click="search">
                    <el-icon>
                      <Search />
                    </el-icon>
                    查询
                  </el-button>
                  <el-button @click="reset">
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 表格区域 -->
            <el-table v-loading="loading"
                      :data="tableData"
                      border
                      :height="tableHeight"
                      style="margin-top: 15px"
                      @select="handleSelect"
                      @select-all="handleSelectAll"
                      @row-click="handleRowClick"
                      ref="tableRef">
              <el-table-column v-if="multiple"
                               type="selection"
                               width="55" />
              <el-table-column prop="name"
                               label="材料名称"
                               min-width="120"
                               align="center" />
              <el-table-column prop="specification"
                               label="型号规格"
                               min-width="120"
                               show-overflow-tooltip
                               align="center" />
              <el-table-column prop="brand"
                               label="品牌"
                               min-width="100"
                               align="center" />
              <el-table-column prop="price"
                               label="单价"
                               min-width="100"
                               align="center">
                <template #default="scope">
                  <span class="price-value">{{ scope.row.price ? `¥${scope.row.price.toFixed(2)}` : '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="priceTwo"
                               label="单价2"
                               min-width="80"
                               align="center">
                <template #default="scope">
                  <span class="price-value">{{ scope.row.priceTwo ? `¥${scope.row.priceTwo.toFixed(2)}` : '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="premium"
                               label="溢价"
                               min-width="80"
                               align="center">
                <template #default="scope">
                  <span class="price-value">{{ scope.row.premium ? `¥${scope.row.premium.toFixed(2)}` : '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark"
                               label="备注"
                               min-width="120"
                               show-overflow-tooltip
                               align="center" />
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="paginationData.currentPage"
                           v-model:page-size="paginationData.pageSize"
                           :page-sizes="[10, 20, 50]"
                           :total="paginationData.total"
                           layout="total, sizes, prev, pager, next"
                           class="pagination"
                           @size-change="getTableData"
                           @current-change="getTableData" />
          </el-col>
          <!-- 右侧内容区 -->
          <el-col :span="3" class="selected-col">
            <div class="selected-materials">
              <div class="selected-header">
                <span>已选物料</span>
                <el-badge :value="selectedMaterials.length" class="item" type="primary" />
              </div>
              <div class="selected-list">
                <div v-if="selectedMaterials.length === 0" class="empty-selected">
                  <el-empty description="暂无选中物料" :image-size="60" />
                </div>
                <div v-else>
                  <div 
                    v-for="(material, index) in selectedMaterials" 
                    :key="material.id"
                    class="selected-item"
                  >
                    <div class="item-content">
                      <div class="item-name" :title="material.name">{{ material.name }}</div>
                      <div class="item-spec" :title="material.specification">{{ material.specification || '无规格' }}</div>
                      <div class="item-price">¥{{ material.price ? material.price.toFixed(2) : '0.00' }}</div>
                    </div>
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="Delete" 
                      circle
                      @click="removeMaterial(material, index)"
                      class="remove-btn"
                    />
                  </div>
                </div>
              </div>
              <div class="selected-footer" v-if="selectedMaterials.length > 0">
                <el-button type="warning" size="small" @click="clearAllSelected">
                  清空全部
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </template>
  </sys-dialog>
</template>

<style scoped lang="scss">
.material-dialog-container {
  padding: 0 0px;
  box-sizing: border-box;
  height: 100%;
  overflow: hidden;
}






  .process-tree {
    height: calc(100vh - 160px);
    overflow: auto;

    :deep(.el-tree-node__content) {
      height: 36px;

      &:hover {
        background-color: #f0f9eb;
      }
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #e1f3d8;
      color: #67c23a;
    }
  }

.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 65px;

  :deep(.el-card__body) {
    padding: 10px;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 180px;
}

.price-value {
  font-weight: 600;
  color: #f56c6c;
}

.selected-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.selected-materials {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  min-height: 500px;
  max-height: 500px;
  display: flex;
  flex-direction: column;

  .selected-header {
    padding: 12px 16px;
    border-bottom: 1px solid #ebeef5;
    background: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: 600;
    font-size: 14px;
    color: #303133;

    .el-badge {
      :deep(.el-badge__content) {
        background-color: #409eff;
      }
    }
  }

  .selected-list {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 8px;
    max-height: calc(100% - 120px); // 确保有明确的最大高度

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;
      
      &:hover {
        background: #a8a8a8;
      }
    }

    .empty-selected {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .selected-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      margin-bottom: 8px;
      background: #f9f9f9;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        background: #ecf5ff;
        border-color: #b3d8ff;
      }

      .item-content {
        flex: 1;
        min-width: 0;

        .item-name {
          font-size: 13px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item-spec {
          font-size: 12px;
          color: #909399;
          margin-bottom: 2px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item-price {
          font-size: 12px;
          font-weight: 600;
          color: #f56c6c;
        }
      }

      .remove-btn {
        margin-left: 8px;
        width: 24px;
        height: 24px;
        
        :deep(.el-icon) {
          font-size: 12px;
        }
      }
    }
  }

  .selected-footer {
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
    background: #f5f7fa;
    text-align: center;
  }
}
</style>
